package com.cictec.middleware.tde.rm.disp.receiver.handler;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.commons.utils.Result;
import com.cictec.middleware.commons.utils.ResultUtil;
import com.cictec.middleware.feign.distribute.MiddlewareDeviceFileUploadService;
import com.cictec.middleware.tde.rm.disp.annotation.HandleMessages;
import com.cictec.middleware.tde.rm.disp.receiver.AbstractReceiverHandler;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage.Header;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0x44TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0xC6PlatformMessage;

/**
 * 结束传输标识
 * 
 * @author wsl
 *
 */
@Component
@HandleMessages(0x44)
public class TerminalEndShortConnectHandler extends AbstractReceiverHandler {
	private static Logger logger = LoggerFactory.getLogger(TerminalEndShortConnectHandler.class);

	@Autowired
	private MiddlewareDeviceFileUploadService middlewareDeviceFileUploadService;

	@SuppressWarnings("rawtypes")
	@Override
	public void handleMessage(TerminalMessage message, IoSession session) {
		Rm0x44TerminalMessage msg = (Rm0x44TerminalMessage) message;
		logger.debug("【0X44结束传输】终端 {} Session {}  header:{}  sendTime:{}", message.getTerminalId(), msg.getSess_Id(), DateUtils.formatDateTime(msg.getCreateTime()), DateUtils.formatDateTime(msg.getHeader().getSendTime()));

		String now_sessionid = msg.getSess_Id();
		String devCode = PMSUtils.isNull(msg.getHeader().getTerminalId());
		Result result = middlewareDeviceFileUploadService.uploadDeviceStaionFileUploadSessionId(devCode, now_sessionid);
		if (ResultUtil.isSuccess(result)) {
			Map data = new HashMap();
			now_sessionid = PMSUtils.isNull(data.get("sessionId"));
		}
		
		// 更新详情
		middlewareDeviceFileUploadService.uploadDeviceStaionFileUploadResult(devCode, now_sessionid, "2", "");

		Header header = new Header(0xC6);
		header.setLineId(msg.getHeader().getLineId());
		header.setTerminalId(msg.getHeader().getTerminalId());
		header.setDataFlag(0);
		Rm0xC6PlatformMessage presc = new Rm0xC6PlatformMessage(header);
		presc.setCreateTime(new Date());
		presc.setFileNameLen(msg.getFileNameLen());
		presc.setFileName(msg.getFileName());
		presc.setSessionIdLen(now_sessionid.length());
		presc.setSess_Id(now_sessionid);

		sendMessageToTerminal(presc, session);

	}

}
